package com.jqb.webservice.ums.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jqb.webservice.ums.vo.User;
import com.jqb.webservice.ums.vo.UserException;

public class UserDao {

	private Map<Integer, User> users = new HashMap<Integer, User>();
	private static UserDao userDao = null;
	public UserDao() {
		User user = new User(1000, "admin", "admin123");
		users.put(user.getId(), user);
	}

	public static UserDao newInstance() {
		if (userDao == null) {
			userDao = new UserDao();
		}
		return userDao;
	}

	public void addUser(User user) {
		Set<Integer> ids = users.keySet();
		if (ids.contains(user.getId())) {
			System.out.println("此用户已存在...");
		} else {
			users.put(user.getId(), user);
		}
	}

	public void deleteUser(int id) {
		Set<Integer> ids = users.keySet();
		if (ids.contains(id)) {
			users.remove(id);
		} else {
			System.out.println("无此用户...");
		}
	}

	public User getUser(int id) {
		Set<Integer> ids = users.keySet();
		User user = null;
		if (ids.contains(id)) {
			user = users.get(id);
		} else {
			System.out.println("无此用户...");
		}
		return user;
	}

	public List<User> getUsers() {
		Set<Integer> ids = users.keySet();
		List<User> userList = new ArrayList<User>();
		for (Integer i : ids) {
			userList.add(users.get(i));
		}
		return userList;
	}

	public void updateUser(User user) {
		users.put(user.getId(), user);
	}

	public User login(String username, String password) throws UserException {
		Set<Integer> ids = users.keySet();
		User user = null;
		for(Integer i : ids){
			user = users.get(i);
			if((user.getUsername().equals(username))&&(user.getPassword().equals(password))){
				System.out.println("登录成功...");
				break;
			}else{
				throw new UserException("用户名或密码错误...");
			}
		}
		return user;
	}
}
